/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.application;

import com.jb.web.bean.FloatPanel;
import com.jb.web.bean.HtmlItem;
import com.jb.web.bean.Page;
import com.jb.web.bean.UIComponentImpl;
import com.jb.web.bean.BeanFactory;
import com.jb.web.context.WebContext;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Processor for internal requests for jb system.
 *
 */
public class InternalProcessor {
    static final private String CHANGE_MODE = "changeMode";
    static final private String EDIT_ACTION = "editAction";
    static final private String AJAX_REQUEST = "AJaxRequest";
    static final private String AJAX_WIZARD = "wizard";
    
    static final private String AJAX_RENDER = "renderChildren";
    static final private String AJAX_RENDER_COMPONENT = "renderComponent";
    static final private String SERVER_EVENT = "serverEvent";
    static final private String SUBMIT_FORM = "processRequest";
    static final private String DIALOG_EVENT = "renderPanel";
    static final private String SET_COMP_VALUE = "change";
    static final private String DROP = "drop";
    static final private String SET_COMP_DIMENSION = "com.jb.ajax.setDim";

    boolean handleRequest(WebContext ctx, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        String action = request.getParameter(EDIT_ACTION);
        if (!ctx.isDeployed() && CHANGE_MODE.equals(action)) {
        //if current page is not designable, we will set it to designable 
            Page page = ctx.getPage();
            if(page.isDesignable())
                ctx.getSession().setRunTime(!ctx.getSession().isRunTime());
            else
                ctx.getSession().setRunTime(false);
            if(page!=null && !ctx.getSession().isRunTime() && !page.isDesignable())
            {//we need to get page define, not the cloned one
                page = ctx.getSession().getPage(ctx, page.getName(), false);
                page.setDesignable(true);
            }
            response.sendRedirect(request.getRequestURI());
            return true;
        }
        
        AjaxServer service = new AjaxServer();
        if (DIALOG_EVENT.equals(action)) {
            service.renderComp(ctx, request, response);
            return true;
        }
        
        if (AJAX_REQUEST.equals(action)) {
            service.processRequest(ctx, request, response);
            return true;
        }
        if (action!=null && action.startsWith(AJAX_WIZARD)) {
            service.wizardAction(ctx, request, response, action);
            return true;
        }
        if (AJAX_RENDER.equals(action)) {
            service.update(ctx, request, response);
            return true;
        }
        
        if(AJAX_RENDER_COMPONENT.equals(action)) {
            service.renderComp(ctx, request, response);
        }
        if (SUBMIT_FORM.equals(action)) {
            service.performAll(ctx, request, response);
            return true;
        }
        if (SERVER_EVENT.equals(action)) {
            service.handleServerEvent(ctx, request, response);
            return true;
        }
        if (SET_COMP_VALUE.equals(action)) {
            service.setComponentValue(ctx, request, response);   
            return true;
        }
        if (DROP.equals(action)) {
            handleDrop(ctx, request);
        }
        if (SET_COMP_DIMENSION.equals(action)) {
            handleSetDim(ctx, request);
        }
        return false;
    }

    //
    //called when a object is dropped on to another, It creates a new component in the
    //target component. The parent component must be type of NamingContainer for 
    //a component to be dropped on. So you can not drop a component to a Link, or Table
    //but you can drop to a cell, panel, page etc.
    //
    private void handleDrop(WebContext ctx, HttpServletRequest request) {
        BeanFactory.addNewComponent(ctx, request.getParameter("id"), request.getParameter("itemType"));
    }

    /**
     * Sets value for a value holder component. This will invoke valueChanged event
     * so that developer can hook application logic on the client event. It also
     * renders the response back if respId is given which is the client id of
     * a component in the request tree.
     * On the client side, element(respId).innerHTML=responseText will render the
     * result.
     * @param ctx
     * @param request
     */

    //handle set dimention of a component 
    private void handleSetDim(WebContext ctx, HttpServletRequest request) {
        String clientId = request.getParameter("clientId");
        String mode = request.getParameter("mode");
        UIComponentImpl hi = null;

        if ("jbToolBox".equals(clientId) && (ctx.getToolBar() != null)) {
            hi = (UIComponentImpl) ctx.getToolBar().getDescendantByClientId(clientId);
        } else if ("jbVariableBox".equals(clientId)) {
            hi = (UIComponentImpl) ctx.getToolBar().getDescendantByClientId(clientId);
        } else {
            hi = (UIComponentImpl) ctx.getRespondTree().getDescendantByClientId(clientId);
        }

        if ((hi != null) && hi instanceof HtmlItem) {
            HtmlItem region = (HtmlItem) hi;
            if(!"moving".equals(mode))
            {
              region.setWidth(request.getParameter("w"));
              region.setHeight(request.getParameter("h"));
            }
           // if (hi instanceof FloatPanel) {
            if(!"sizing".equals(mode) && hi instanceof FloatPanel)
            {
                FloatPanel fp = (FloatPanel) hi;
                fp.setTop(request.getParameter("y"));
                fp.setLeft(request.getParameter("x"));
            }
            region.valueChanged(ctx);
        }
    }
}
